package com.ihighest.app.infox.activity;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.adapter.ColumnListAdapter;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.InitShare;
import com.umeng.socialize.bean.SHARE_MEDIA;

/**
 * 专栏名称界面
 * 
 * @author lkx Created at 2015-10-10 上午10:55:36
 * @version 1.0
 */
public class ColumnNameActivity extends BaseActivity implements OnClickListener {

	private ActivityTitle title;
	private ColumnListAdapter adapter;
String  name="";
	JSONArray array;

	TextView tv_title, tv_count, tv_subscription, emptyView;

	ImageView iv_logo;

	String id;

	int count = -1;
	TextView auThorMemo, columnMemo;
	PullToRefreshListView pullToRefresh;

	int page = 1;
	long time = 0;
	private TextView lookMoreMemo;
	private PopupWindow mPopupWindow;
	private InitShare share;
	private SHARE_MEDIA shareTo;
	String shearcontent = "";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_columnname);

		id = getIntent().getStringExtra("cid");
		title = (ActivityTitle) findViewById(R.id.ColumnNameActivityTitle);
		title.setTitle("");
		title.setViewVersible(title.rightLayout, title.titleBack);
		title.setViewGone(title.titleSetting, title.titleRefresh, title.titleMsg, title.titleSearch);
		title.setOtherImg(R.drawable.infox_title_share);
		auThorMemo = (TextView) findViewById(R.id.authorBriefIntroduction);
		columnMemo = (TextView) findViewById(R.id.columnIntroduction);
		lookMoreMemo = (TextView) findViewById(R.id.lookMoreMemo);
		share = new InitShare(this);

		tv_title = (TextView) findViewById(R.id.tv_title);
		tv_count = (TextView) findViewById(R.id.tv_count);
		tv_subscription = (TextView) findViewById(R.id.tv_subscription);

		iv_logo = (ImageView) findViewById(R.id.iv_logo);
		lookMoreMemo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (lookMoreMemo.getText().equals("查看更多")) {
					columnMemo.setMaxLines(100);
					lookMoreMemo.setText("收起简介");

				} else if (lookMoreMemo.getText().equals("收起简介")) {
					columnMemo.setMaxLines(2);
					lookMoreMemo.setText("查看更多");
				}

			}
		});
		tv_subscription.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {

				if (TextUtils.isEmpty(SharedPreferencesKit.getString(ColumnNameActivity.this, Const.SP_KEY_USER_ID))) {
					Intent intent = new Intent(ColumnNameActivity.this, LoginActivity.class);
					ColumnNameActivity.this.startActivity(intent);
					return;
				}

				if (view.getTag().equals("0")) {
					// quxiao
					submit("2");
					tv_subscription.setTag("1");
					tv_subscription.setText("订阅");
					tv_subscription.setBackgroundResource(R.drawable.infox_orange_frame);
					tv_subscription.setTextColor(Color.parseColor("#fa6400"));
					ToastKit.showShort(getApplicationContext(), "已取消");

				} else if (view.getTag().equals("1")) {
					// dingyue
					submit("1");
					tv_subscription.setTag("0");
					tv_subscription.setText("取消订阅");
					tv_subscription.setBackgroundResource(R.drawable.infox_searchitem_third);
					tv_subscription.setTextColor(Color.parseColor("#ffffff"));
					ToastKit.showShort(getApplicationContext(), "已订阅成功");
				}

			}
		});

		title.titleOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// share
				initSharePupoVindow();
				showPupop();
			}
		});

		getintentdata();

		emptyView = (TextView) findViewById(R.id.emptyView);
		emptyView.setText("加载中...");
		emptyView.setVisibility(View.VISIBLE);

		adapter = new ColumnListAdapter(this);

		pullToRefresh = (PullToRefreshListView) findViewById(R.id.pullToRefresh);
		pullToRefresh.setVisibility(View.GONE);
		pullToRefresh.setAdapter(adapter);
		pullToRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				page = 1;
				getdata();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				page++;
				getdata();
			}
		});

		pullToRefresh.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					Intent intent = new Intent(ColumnNameActivity.this, InformationalContentActivity.class);
					intent.putExtra("newsId", array.getJSONObject(arg2 - 1).getString("id"));
					intent.putExtra("from", "cloumn");
					intent.putExtra("clumid", id);
					intent.putExtra("clumname",name);

					if (tv_subscription.getTag().equals("0")) {
						intent.putExtra("isSubscribes", true);
					}else{
						intent.putExtra("isSubscribes", false);
					}

					startActivity(intent);
				} catch (JSONException e) {
					// pass
				}
			}
		});

		getdata();
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getintentdata();
	}

	/**
	 * 
	 * 获取传递过来的内容
	 * 
	 * 
	 * @author yyh Created at 2015-11-11 下午4:33:58
	 */
	private void getintentdata() {
		Api.get("columnist/details", ApiParam.create().addParam("id", id), new ApiCallback(this) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					try {
						name=result.getData().getString("title");
						tv_title.setText(name);
						title.setTitle(name);
						count = result.getData().getInt("count");
						if (count > 0) {
							tv_count.setText(result.getData().getInt("count") + "人订阅");
						} else {
							tv_count.setVisibility(View.INVISIBLE);
						}

						String Memo = result.getData().getString("memo");
						if (TextUtils.isEmpty(result.getData().getString("writerMemo"))) {
							auThorMemo.setText("暂无作者信息");
						} else {
							auThorMemo.setText(result.getData().getString("writerMemo"));
						}
						columnMemo.setText(Memo);

						// DisplayImageOptions defaultOptions = new
						// DisplayImageOptions.Builder()
						// .showImageForEmptyUri(R.drawable.infox_img_loadrong).showImageOnFail(R.drawable.infox_img_loadrong)
						// .showImageOnLoading(R.drawable.infox_img_loadrong).cacheInMemory(true).cacheOnDisc(true).build();
						// ImageLoader.getInstance().displayImage(result.getData().getString("image"),
						// iv_logo, defaultOptions);
						AppKit.SetNormalImg(result.getData().getString("image"), iv_logo);
						if (result.getData().getString("isSubscribes") != null && result.getData().getString("isSubscribes").equals("true")) {
							// 已订阅
							tv_subscription.setTag("0");
							tv_subscription.setText("取消订阅");
							tv_subscription.setBackgroundResource(R.drawable.infox_searchitem_third);
							tv_subscription.setTextColor(Color.parseColor("#ffffff"));

						} else {
							// 没订阅
							tv_subscription.setTag("1");
							tv_subscription.setText("订阅");
							tv_subscription.setBackgroundResource(R.drawable.infox_orange_frame);
							tv_subscription.setTextColor(Color.parseColor("#fa6400"));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, this);

	}

	private void getdata() {
		Api.get("columnist/infos", ApiParam.create().addParam("cid", id).addParam("page", page), new ApiCallback(this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					if (result.getDatas() != null && result.getDatas().length() > 0) {
						emptyView.setVisibility(View.GONE);
						pullToRefresh.setVisibility(View.VISIBLE);
						if (page == 1) {
							array = adapter.setDatas(result.getDatas());
						} else {
							array = adapter.appendDatas(result.getDatas());
						}
					} else if (page == 1) {
						emptyView.setText("暂无数据");
						emptyView.setVisibility(View.VISIBLE);
						pullToRefresh.setVisibility(View.GONE);
					} else {
						page--;
					}
				} else if (page == 1) {
					emptyView.setText("暂无数据");
					emptyView.setVisibility(View.VISIBLE);
					pullToRefresh.setVisibility(View.GONE);
				}
				pullToRefresh.onRefreshComplete();
			}

			@Override
			public void handleFailure(Exception e, String msg) {
				if (page == 1) {
					emptyView.setText("暂无数据");
					emptyView.setVisibility(View.VISIBLE);
					pullToRefresh.setVisibility(View.GONE);
				} else {
					page--;
				}
				pullToRefresh.onRefreshComplete();
			}
		}, this);

	}

	protected void submit(final String type) {
		Api.post("me/followColumnist", ApiParam.create().addParam("id", id).addParam("type", type), new ApiCallback(this, true) {

			@Override
			public void handleSuccess(ApiResult result) {
				if (result.getCode() == 100) {
					if (type.equals("1")) {
						tv_count.setText((++count) + "人订阅");
					} else {
						--count;
						if (count > 0) {
							tv_count.setText(count + "人订阅");
						} else {
							tv_count.setVisibility(View.INVISIBLE);
						}
					}
					Intent intent = new Intent();
					intent.setAction(Const.REFLASH);
					ColumnNameActivity.this.sendBroadcast(intent);
					Log.e("columnname", "ok");
				}
			}

			@Override
			public void handleFailure(Exception e, String msg) {

			}
		}, this);

	}

	private void initSharePupoVindow() {

		LayoutInflater layoutInflater = LayoutInflater.from(this);
		View popupWindow = layoutInflater.inflate(R.layout.infox_activity_content_share_popu, null);

		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */
		popupWindow.findViewById(R.id.shareToWeixin).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToFriendCircle).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToMessage).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToQQ).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareToWeb).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareEmail).setOnClickListener(this);
		popupWindow.findViewById(R.id.transpond).setOnClickListener(this);
		popupWindow.findViewById(R.id.shareCopyLink).setOnClickListener(this);
		popupWindow.findViewById(R.id.cancle).setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		shearcontent = "《" + tv_title.getText().toString() + "》" + "你不可错过的农资精品专栏";

		String url = "http://info.nzdb.com.cn/app";
		try {
			url = SharedPreferencesKit.getJsonObject(this, Const.SP_KEY_CONFIG_JSON).getString("downAppUrl") + "?code="
					+ SharedPreferencesKit.getString(this, Const.USER_InvitedCode) + "&mid="
					+ SharedPreferencesKit.getString(this, Const.SP_KEY_USER_MID);
		} catch (Exception e) {

		}

		switch (view.getId()) {
		case R.id.shareToWeixin:
			shareTo = SHARE_MEDIA.WEIXIN;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToFriendCircle:
			shareTo = SHARE_MEDIA.WEIXIN_CIRCLE;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToMessage:
			shareTo = SHARE_MEDIA.SMS;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToQQ:
			shareTo = SHARE_MEDIA.QQ;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareToWeb:
			shareTo = SHARE_MEDIA.SINA;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.shareEmail:
			shareTo = SHARE_MEDIA.EMAIL;
			share.setMyShareContent(shearcontent, url);
			share.isShareSuccess(shareTo);
			break;
		case R.id.transpond:
			ToastKit.showShort(getApplicationContext(), Const.UN_FINISH_ALERT);
			break;
		case R.id.shareCopyLink:
			ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			if (Build.VERSION.SDK_INT >= 11) {
				ClipData clipData = ClipData.newPlainText("App下载链接", url);
				clip.setPrimaryClip(clipData);
			} else {
				clip.setText(url);
			}

			break;
		case R.id.cancle:
			mPopupWindow.dismiss();
			break;

		}
	}

	private void showPupop() {

		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		} else {
			mPopupWindow.showAtLocation(findViewById(R.id.id_parent), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
		}

	}

}
